/**
 * 微信公众平台开发模式(JAVA) SDK
 * (c) 2012-2014 ____′↘夏悸 <wmails@126.cn>, MIT Licensed
 * http://www.jeasyuicn.com/wechat
 */
package com.gson.oauth;

import cc.bluemc.platform.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import com.gson.bean.UserInfo;
import com.gson.util.HttpKit;
import com.gson.util.Status;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
/**
 * 微信Oauth和支付工具类
 *
 * @author L.cm
 * @date 2013-11-14 下午4:42:42
 */
public class Oauth {

    private static final String CODE_URI = "http://open.weixin.qq.com/connect/oauth2/authorize";
    private static final String TOKEN_URI = "https://api.weixin.qq.com/sns/oauth2/component/access_token";
    private static final String USERINFO="https://api.weixin.qq.com/sns/userinfo";
    private static final String REFRESH_TOKEN_URI = "https://api.weixin.qq.com/sns/oauth2/refresh_token";


    public Oauth() {
    }
    /**
     * 请求code,微信回调到targetUrl，带有code参数
     * @return
     * @throws java.io.UnsupportedEncodingException
     */
    public String getCode(String appid,String targetUrl,String state,String component_appid) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appid);
        params.put("response_type", "code");
        params.put("redirect_uri", targetUrl);
        params.put("scope", "snsapi_base"); // snsapi_base（不弹出授权页面，只能拿到用户openid）snsapi_userinfo
        params.put("component_appid",component_appid);//服务方APPID
        // （弹出授权页面，这个可以通过 openid 拿到昵称、性别、所在地）
        if (StringUtils.isBlank(state)) {

        }
        params.put("state", state+"#wechat_redirect");
        String para = Pay.createSign(params, false);
        return  CODE_URI + "?" + para;
    }

    /**
     * 通过code 换取 access_token
     * @param code
     * @return
     * @throws java.io.IOException
     * @throws java.security.NoSuchProviderException
     * @throws java.security.NoSuchAlgorithmException
     * @throws java.security.KeyManagementException
     * //            { "access_token" :"XWfsbLyIkPVKNS0hW8B19b-GyWTmIBYE9_bywTw0vFw1PnX5JvA8XY5HQluh2Oz93Eu2HGA9RXjgbp5v6zJal1n7kORbtW-MuXEiPvBhe6xHxc8IByQLZ5Z8YmkzcVy-",
    //                    "expires_in" :7200,
    //                    "refresh_token" :"Pw5el298QAE-Dc0_PbXprwahBzbxZArXg4wBW-XJ99V9RnY6caA6BL6xYudrk9NR6e3VLZgXOvvCh1-zjc0sSF6uysgnWGKrlg1T8CZmdXjVlBL0faW6AnlWB240MZeK",
    //                    "openid" :"oNjcls3RsT8-8Xg3ZCuLvSsRKXHI",
    //                    "scope" :"snsapi_base",
    //                    "unionid" :"oGXsgwFpBB_vXl7bDiTbrvpe91iY" }
     */
    public String getToken(String appid,String code,String componentAppId, String componentAccessToken) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appid);
        params.put("component_appid", componentAppId);
        params.put("component_access_token",componentAccessToken);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        return HttpKit.get(TOKEN_URI, params);
    }

    /**
     * 微信授权页面回调获取用户
     * @param appid
     * @param code
     * @param componentAppId
     * @param componentAccessToken
     * @return
     * @throws Exception
     */
    public UserInfo getUserInfo(String appid,String code,String componentAppId, String componentAccessToken) throws Exception {
        String token = getToken(appid, code, componentAppId, componentAccessToken);
        JSONObject obj = JSONObject.parseObject(token);
        if(obj.get("errcode") != null){
            throw new ServiceException("通过code 换取 access_token:"+ Status.is(obj.getInteger("errcode")));
        }
         UserInfo userInfo = getUserInfo(obj.getString("access_token"), obj.getString("openid"));
        return userInfo;
    }

    /**
     * 微信授权页面回调获取用户
     * @param access_token
     * @param openid
     * @return
     * @throws Exception
     */
    public UserInfo getUserInfo(String access_token,String openid) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", access_token);
        params.put("openid", openid);
        params.put("lang", "zh_CN");
        params.put("grant_type", "authorization_code");
        String userInfoJson = HttpKit.get(StringUtils.join(USERINFO,"?lang=zh_CN&access_token=",access_token,"&openid=",openid));;
        JSONObject obj = JSONObject.parseObject(userInfoJson);
        if(obj.get("errcode") != null){
            throw new ServiceException("微信授权页面回调获取用户:"+ Status.is(obj.getInteger("errcode")));
        }
        UserInfo userInfo = obj.toJavaObject(UserInfo.class);
        return userInfo;
    }

    /**
     * 刷新 access_token
     * @param refreshToken
     * @return
     * @throws java.io.IOException
     * @throws java.security.NoSuchProviderException
     * @throws java.security.NoSuchAlgorithmException
     * @throws java.security.KeyManagementException
     */
//    public String getRefreshToken(String refreshToken) throws Exception {
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("appid", getAppid());
//        params.put("grant_type", "refresh_token");
//        params.put("refresh_token", refreshToken);
//        return HttpKit.get(REFRESH_TOKEN_URI, params);
//    }
}
